package com.minicat.servlet;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author liangzj
 * @date 2021/3/28 15:38
 */
public class Request {

    private String host;
    private String method; // 请求方式，eg:get/post
    private String url; // eg:/index.html

    private InputStream inputStream; // 其他属性从输入流中获取

    public Request(InputStream inputStream) throws IOException {
        this.inputStream = inputStream;

        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }
        byte[] bytes = new byte[count];
        inputStream.read(bytes);

        String inputStr = new String(bytes);
        String[] headerLine = inputStr.split("\\n");
        String firstLineStr = headerLine[0]; // GET / HTTP/1.1
        String hostLineStr = headerLine[1]; // Host: localhost:8080

        String[] protocolLine = firstLineStr.split(" ");
        this.method = protocolLine[0];
        this.url = protocolLine[1];
        this.host = hostLineStr.split(" ")[1].split(":")[0];

        System.out.println(toString());
    }

    @Override
    public String toString() {
        return "Request{" +
                "host='" + host + '\'' +
                ", method='" + method + '\'' +
                ", url='" + url + '\'' +
                ", inputStream=" + inputStream +
                '}';
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }
}
